//
//  MQMyStoreViewController.m
//  meiquan
//
//  Created by hejingjin on 2017/10/23.
//  Copyright © 2017年 mq. All rights reserved.
//

#import "MQMyStoreViewController.h"
#import "JHCollectionViewFlowLayout.h"
#import "MQHomeProductCell.h"
#import "MQBaseUserInfoModel.h"

#import "MQProtypeModel.h"
#import "MQProductListModel.h"
#import "MQProductViewController.h"
#import "MQHomeProductCollectionViewCell.h"
#import "MQadviews.h"
#import "MQAdmodels.h"
#import "MQAdDetailViewController.h"
@interface MQMyStoreViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property(nonatomic,strong)NSMutableArray *typearray;

@property(nonatomic,strong)UIScrollView *typescrollview;

@property(nonatomic,strong)NSMutableArray *buttonarray;
@property(nonatomic,strong)NSMutableArray *viewarray;
@property(nonatomic,strong)NSArray *titlearray;
@property(nonatomic,strong)NSMutableArray *tiltearrays;


@property(nonatomic,strong)UICollectionView *storecollectionview;


@property(nonatomic,assign)NSInteger currenttype;

@property(nonatomic,strong)NSMutableArray *dataSoure;

@property(nonatomic,assign)BOOL isbig;

@property(nonatomic,strong)MQadviews *adviews;

@property(nonatomic,strong)MQAdmodels *admodels;

@end

@implementation MQMyStoreViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"我的商城";
    _isbig = YES;
    
    _typearray = [NSMutableArray array];
    _buttonarray = [NSMutableArray array];
    _viewarray = [NSMutableArray array];
    MQProtypeModel *model = [MQProtypeModel new];
    model.ID = @"0";
    model.name = @"全部";
    [_typearray addObject:model];
    
    _dataSoure = [NSMutableArray array];
    _currenttype = -1;
    //    _titlearray = @[@"全部",@"全部1",@"全部2",@"全部3",@"全部4",@"全部5",@"全部6"];
    [self setUpMainInterface];
    
    [self getcategory];
    
    [self getaddata];
    
}

-(void)getaddata{
    
    NSArray *array = @[@"page1",@"@page2",@"page3"];
    int x = arc4random() % 3;
    
    MQBaseUserInfoModel *userinfo = [MQBaseUserInfoModel shareInstant];
    [userinfo loadUserinfoFromSadeBox];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    [param setValue:userinfo.userId forKey:@"userId"];
    [param setValue:array[x] forKey:@"code"];
    
    [MQRequestTools POSTWithMethod:adv_index params:param success:^(id json) {
        
        NSDictionary *dic = [json valueForKey:@"data"];
        _admodels = [MQAdmodels mj_objectWithKeyValues:dic];
        if (_admodels.advId) {
            [_adviews.adimageviews sd_setImageWithURL:[NSURL URLWithString:_admodels.pic] placeholderImage:[UIImage imageNamed:@""]];
        }else{
            _adviews.bst_height = 0;
            _storecollectionview.bst_y = MAX_Y(_typescrollview.frame);
            _storecollectionview.bst_height =BSTScreenH -MAX_Y(_typescrollview.frame);
        }
        
        
        
        UITapGestureRecognizer *tapGesturRecognizer=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
        [_adviews addGestureRecognizer:tapGesturRecognizer];
        
    } failure:^(NSError *error) {
        
    }];
    
    
}

-(void)tapAction:(UITapGestureRecognizer *)obj{
    NSLog(@"%@",_admodels.url);
    MQAdDetailViewController *advc = [[MQAdDetailViewController alloc] init];
    advc.url = _admodels.url;
    advc.type = _admodels.type;
    [self.navigationController pushViewController:advc animated:YES];
}

-(void)getstoreProduct{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    MQBaseUserInfoModel *userinfo = [MQBaseUserInfoModel shareInstant];
    [userinfo loadUserinfoFromSadeBox];
    
    [param setValue:userinfo.userId forKey:@"userId"];
    [param setValue:@"1" forKey:@"page"];
    [param setValue:@"20" forKey:@"limit"];
    MQProtypeModel *model = _typearray[_currenttype];
    [param setValue:model.ID forKey:@"seriesId"];
    
    [MQRequestTools POSTWithMethod:mall_index params:param success:^(id json) {
        [_dataSoure removeAllObjects];
        NSArray *array = [json valueForKey:@"data"];
        for (NSDictionary *dic in array) {
            MQProductListModel *model = [MQProductListModel mj_objectWithKeyValues:dic];
            [_dataSoure addObject:model];
        }
        [_storecollectionview reloadData];
    } failure:^(NSError *error) {
        
    }];
    
    
    
}

-(void)getcategory{
    
    
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    MQBaseUserInfoModel *userinfo = [MQBaseUserInfoModel shareInstant];
    [userinfo loadUserinfoFromSadeBox];
    
    [param setValue:userinfo.userId forKey:@"userId"];
    
    
    [MQRequestTools POSTWithMethod:series_getByUserId params:param success:^(id json) {
        
        NSArray *data = [json valueForKey:@"data"];
        
        for (NSDictionary *dic in data) {
            MQProtypeModel *model = [MQProtypeModel mj_objectWithKeyValues:dic];
            [_typearray addObject:model];
        }
        
        [self reloadtypeview];
        
        [self getstoreProduct];
        
    } failure:^(NSError *error) {
        
    }];
    
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


-(void)reloadtypeview{
    
    
    
    for (int i = 0; i < _buttonarray.count; i ++) {
        
        UIButton *button = _buttonarray[i];
        UIView *view = _viewarray[i];
        [button removeFromSuperview];
        [view removeFromSuperview];
        
    }
    
    [_buttonarray removeAllObjects];
    [_viewarray removeAllObjects];
    CGFloat x = 0;
    CGFloat w = 0;
    for (int i = 0; i < _typearray.count; i ++) {
        
        MQProtypeModel *model = _typearray[i];
        
        NSString *content = model.name;
        UIFont *font = [UIFont systemFontOfSize:14];
        CGSize size = CGSizeMake(MAXFLOAT, 43.0f);
        CGSize buttonSize = [content boundingRectWithSize:size
                                                  options:NSStringDrawingTruncatesLastVisibleLine  | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                               attributes:@{ NSFontAttributeName:font}
                                                  context:nil].size;
        
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x + 20, 0, buttonSize.width, 43)];
        
        [button setTitle:model.name forState:UIControlStateNormal];
        
        [button setTitleColor:BSTColorFromRGB(0x333333) forState:UIControlStateNormal];
        [button setTitleColor:BSTColorFromRGB(0xff8e01) forState:UIControlStateSelected];
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        
        UIView *bottomview = [[UIView alloc] initWithFrame:CGRectMake(x + 20, 43, buttonSize.width, 2)];
        bottomview.hidden = YES;
        bottomview.backgroundColor = BSTColorFromRGB(0xff8e01);
        button.tag = 10000+ i;
        [button addTarget:self action:@selector(butttonpressed:) forControlEvents:UIControlEventTouchUpInside];
        if (i == 0) {
            button.selected = YES;
            bottomview.hidden = NO;
        }
        [_buttonarray addObject:button];
        [_viewarray addObject:bottomview];
        
        [_typescrollview addSubview:button];
        [_typescrollview addSubview:bottomview];
        _currenttype = 0;
        if (i == _titlearray.count - 1) {
            [_typescrollview setContentSize:CGSizeMake(MAX_X(button.frame) + 15, 45)];
        }
        x = MAX_X(button.frame);
    }
}

-(void)butttonpressed:(UIButton *)sender{
    NSInteger index = sender.tag - 10000;
    
    if (index == _currenttype) {
        return;
    }else{
        [_dataSoure removeAllObjects];
      
        [_storecollectionview reloadData];
        for (int i =0; i < _buttonarray.count; i++) {
            
            UIButton *button = _buttonarray[i];
            UIView *lineview = _viewarray[i];
            if (index == i) {
                button.selected = YES;
                lineview.hidden = NO;
            }else{
                button.selected = NO;
                lineview.hidden = YES;
            }
            
            
            
        }
        _currenttype =index;
        [self getstoreProduct];
    }
    
    
    
}

-(void)setUpMainInterface{
    
    
    self.view.backgroundColor = BSTColorFromRGB(0xefefef);
    
    UIView *topview = [[UIView alloc] initWithFrame:CGRectMake(0, NAVHEIGHT, BSTScreenW, 45)];
    
    UIButton *cssbutton = [[UIButton alloc] initWithFrame:CGRectMake(BSTScreenW - 60, 0, 60, 45)];
    [cssbutton setImage:[UIImage imageNamed:@"qiehuan"] forState:UIControlStateNormal];
    [topview addSubview:cssbutton];
    [cssbutton addTarget:self action:@selector(cssbuttonPressed) forControlEvents:UIControlEventTouchUpInside];
    topview.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:topview];
    
    
    _typescrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, NAVHEIGHT, BSTScreenW - 60, 45)];
    _typescrollview.showsVerticalScrollIndicator = NO;
    _typescrollview.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_typescrollview];
    
    
    _adviews = [MQadviews loadadviews];
    _adviews.bst_x = 0;
    _adviews.bst_width = BSTScreenW;
    _adviews.bst_height = 70 *Persion;
    _adviews.bst_y = MAX_Y(_typescrollview.frame);
    [self.view addSubview:_adviews];
    
    
    [self.view addSubview:self.storecollectionview];
}


-(void)cssbuttonPressed{
    _isbig = !_isbig;
    [self.storecollectionview reloadData];
}

-(UICollectionView *)storecollectionview{
    
    if (!_storecollectionview) {
        
        self.automaticallyAdjustsScrollViewInsets = NO;
        //
        
        
        JHCollectionViewFlowLayout *jhFlowLayout = [[JHCollectionViewFlowLayout alloc] init];
        jhFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        
        //初始化布局
        UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
        flowLayout.minimumInteritemSpacing = 0;
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, NAVHEIGHT + 45 + 70 * Persion, BSTScreenW, BSTScreenH - NAVHEIGHT - 45 - 70 *Persion) collectionViewLayout:jhFlowLayout];
        collectionView.backgroundColor = BSTColorFromRGB(0xefefef);
        
        _storecollectionview = collectionView;
        
        _storecollectionview.delegate = self;
        _storecollectionview.dataSource = self;
        //注册cell
        //1.轮播cell
        //        [collectionView registerClass:[MQHomeProductCell class] forCellWithReuseIdentifier:@"homepagecellid"];
        
        //1.轮播cell
        //        [collectionView registerClass:[AdvertisementCollectionViewCell class] forCellWithReuseIdentifier:@"advercell"];
        
        
        //        [collectionView registerClass:[CategoryCollectionViewCell class] forCellWithReuseIdentifier:@"categorycell"];
        
        UINib *floorhomepagecellNib = [UINib   nibWithNibName:NSStringFromClass([MQHomeProductCell class]) bundle:[NSBundle mainBundle]];
        
        [collectionView registerNib:floorhomepagecellNib forCellWithReuseIdentifier:@"homepagecellid"];
        
        
        UINib *floorhomexiaonib = [UINib nibWithNibName:NSStringFromClass([MQHomeProductCollectionViewCell class]) bundle:[NSBundle mainBundle]];
        
        [collectionView registerNib:floorhomexiaonib forCellWithReuseIdentifier:@"homepagecellids"];
        
        
        
    }
    return _storecollectionview;
}

- (UIColor *)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout backgroundColorForSection:(NSInteger)section
{
    //    if (section < 2) {
    //        return [UIColor whiteColor];
    //    }else{
    return BSTColorFromRGB(0xefefef);
    //    }
}




-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    MQHomeProductCell *categorycell = [collectionView dequeueReusableCellWithReuseIdentifier:@"homepagecellid" forIndexPath:indexPath];
    MQProductListModel *model = _dataSoure[indexPath.row];
    categorycell.productnameLabel.text = model.name;
    [categorycell.productcellimageview sd_setImageWithURL:[NSURL URLWithString:model.pic] placeholderImage:[UIImage imageNamed:plasces]];
    categorycell.productpricelabel.text = [NSString stringWithFormat:@"¥ %@",model.price];
    categorycell.propaycountlabel.text = [NSString stringWithFormat:@"%ld人付款",model.sales];
    MQHomeProductCollectionViewCell *cells = [collectionView dequeueReusableCellWithReuseIdentifier:@"homepagecellids" forIndexPath:indexPath];
    
    [cells.productimageview sd_setImageWithURL:[NSURL URLWithString:model.pic] placeholderImage:[UIImage imageNamed:plasces]];
    cells.pricelabels.text = [NSString stringWithFormat:@"¥ %@",model.price];
    cells.nameLabels.text = model.name;
    
    cells.fukuanlabel.text =  [NSString stringWithFormat:@"%ld人付款",model.sales];
    
    if (model.unit) {
        cells.kucunlabels.text = [NSString stringWithFormat:@"库存：%ld%@",model.stocks,model.unit];
    }else{
        cells.kucunlabels.text = [NSString stringWithFormat:@"库存：%ld",model.stocks];
    }
    
    
    cells.backgroundColor = [UIColor whiteColor];
    if (_isbig) {
        return categorycell;
    }else{
        return cells;
    }

    
    
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    MQProductListModel *model = _dataSoure[indexPath.row];
    MQProductViewController *productvc = [[MQProductViewController alloc] init];
    productvc.model = model;
    [self.navigationController pushViewController:productvc animated:YES];
}


//item 之间的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    CGFloat proportion = BSTScreenW/375;
    
    
    return 10 *proportion;
    
    
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    
    CGFloat proportion = BSTScreenW/375;
    
    
    return 0.f;
    
    
}

//collectionview的Item大小

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGSize size;
    
    CGFloat proportion = BSTScreenW/375;
    
    
    if (_isbig) {
        size = CGSizeMake(184 *proportion, 251 * proportion);
    }else{
        size =  CGSizeMake(375 *proportion, 110 * proportion);
    }
    
    
    return size;
}

//返回每一个sction中item个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    NSInteger index;
    
    
    return _dataSoure.count;
    
    
}

//section个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    //固定4个＋楼层个数
    return 1;
    
}

//每一个section的间隔
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    CGFloat proportion = BSTScreenW/375;
    
    
    return UIEdgeInsetsMake(10, 0 *proportion, 10,  0*proportion);
    
    
    
}

@end
